<?php
namespace app\common\api;

/**
 * 飞书接口
 * @author Sam
 * @date 2022-10-25
 */
class Feishu {

    private $app_id            = 'cli_a3dd379cdb3bd00d';      // 飞书appId
    private $app_secret        = 'hOWvTu1XpPUGKMYo9s9wphZ4FjJDd7Xm';  // 飞书app_secret
    private $auth_url          = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal'; // app_access_token接口
    private $auth_url2         = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal'; // tenant_access_token接口
    private $access_token_url  = 'https://open.feishu.cn/open-apis/authen/v1/access_token'; // 根据登录预授权码 code 获取 user_access_token
    private $approval_url      = 'https://open.feishu.cn/open-apis/approval/v4/instances'; // 根据 approval_code 批量获取审批实例的 instance_code，用于拉取租户下某个审批定义的全部审批实例
    private $user_info_url     = 'https://open.feishu.cn/open-apis/authen/v1/user_info'; // 通过 user_access_token 获取登录用户的信息。
    private $instances_url     = 'https://open.feishu.cn/open-apis/approval/v4/instances/query'; // 通过 user_id 查询实例列表
    /**
     * 获取应用 app_access_token
     * @return void
     * @author Sam
     * @date 2022-10-25
     */
    public function  get_app_access_token(){
        $redis  = redis_instance();
        $key    = "FeishuAppAccessToken:{$this->app_id}";
        if($result = $redis->get($key)){
            return $result;
        }
        $data = [];
        $data['header'] = ['Content-Type: application/json; charset=utf-8'];
        $data['data']   = json_encode([
            'app_id' => $this->app_id,
            'app_secret'  => $this->app_secret
        ]);
        $result = curl('post',$this->auth_url,$data);
        $result = json_decode($result,true);
        if(isset($result['msg']) && $result['msg'] == 'ok'){
            $redis->set($key,$result['app_access_token'],$result['expire'] - 120);
            return $result['app_access_token'];
        }else{
            exception($result['msg']);
        }
    }

        /**
     * 获取应用 tenant_access_token
     * @return void
     * @author Sam
     * @date 2022-10-25
     */
    public function  get_tenant_access_token(){
        $redis  = redis_instance();
        $key    = "FeishuTenantAccessToken:{$this->app_id}";
        if($result = $redis->get($key)){
            return $result;
        }
        $data = [];
        $data['header'] = ['Content-Type: application/json; charset=utf-8'];
        $data['data']   = json_encode([
            'app_id' => $this->app_id,
            'app_secret'  => $this->app_secret
        ]);
        $result = curl('post',$this->auth_url2,$data);
        $result = json_decode($result,true);
        if(isset($result['msg']) && $result['msg'] == 'ok'){
            $redis->set($key,$result['tenant_access_token'],$result['expire'] - 120);
            return $result['tenant_access_token'];
        }else{
            exception($result['msg'] );
        }
    }


   /**
    * 获取用户信息
    * @param string $code 登录code
    * @return void
    * @author Sam
    * @date 2022-10-25
    */
    public function  get_user_access_token($code){
        if(!$code){
            json_response(0,'缺少CODE');
        }
        $app_access_token = $this->get_app_access_token();
        $data = [];
        $data['header'] = array(
            'Authorization: Bearer '.$app_access_token,
            'Content-Type: application/json; charset=utf-8'
        );
        $data['data']   = json_encode([
            'grant_type' => 'authorization_code',
            'code'  => $code
        ]);
        $result = curl('post',$this->access_token_url,$data);
        $result = json_decode($result,true);
        if(isset($result['code']) && $result['code'] == 0){
            return $result['data'];
        }else{
            exception($result['msg'] );
        }
    }

    /**
     * 获取用户详情
     * @param [type] $token
     * @return void
     * @author Sam
     * @date 2022-10-26
     */
    public function  get_user_info_by_token($token){
        if(!$token){
            json_response(0,'缺少token');
        }
        $data = [];
        $data['header'] = array(
            'Authorization: Bearer '.$token,
        );
        $result = curl('get',$this->user_info_url,$data);
        $result = json_decode($result,true);
        if(isset($result['code']) && $result['code'] == 0){
            return $result['data'];
        }else{
            exception($result['msg'] );
        }
    }

    /**
     * 该接口通过不同条件查询审批系统中符合条件的审批实例列表
     * @param [type] $user_id
     * @return void
     * @author Sam
     * @date 2022-10-26
     */
    public function  get_user_approval_by_id($user_id){
        if(!$user_id){
            json_response(0,'缺少user_id');
        }
        $data = [];
        $data['header'] = array(
            'Authorization: Bearer '.$this->get_tenant_access_token(),
            'Content-Type: application/json; charset=utf-8'
        );
        $data['data']   = json_encode([
            'user_id' => $user_id
        ]);
        $result = curl('post',$this->instances_url.'?page_size=10&user_id_type=user_id',$data);
        $result = json_decode($result,true);
        if(isset($result['code']) && $result['code'] == 0){
            return $result['data'];
        }else{
            exception($result['msg'] );
        }
    }

    /**
     * 批量获取审批实例
     * @param string $approval_code 审批定义唯一标识
     * @param string $start_time 审批实例创建时间区间
     * @param string $end_time  审批实例创建时间区间
     * @return void
     * @author Sam
     * @date 2022-10-25
     */
    public function get_approval_list($approval_code,$start_time,$end_time){
        if(!$approval_code){
            json_response(0,'缺少审批定义唯一标识');
        }
        if(!$start_time || !$end_time){
            json_response(0,'缺少审批实例时间区间');
        }
        $tenant_access_token = $this->get_tenant_access_token();
        $data = [];
        $data['header'] = ['Authorization:Bearer '.$tenant_access_token];
        $result = curl('get',$this->approval_url.'?approval_code='.$approval_code.'&start_time='.$start_time.'&end_time='.$end_time,$data);
        $result = json_decode($result,true);
        if(isset($result['code']) && $result['code'] == 0){
            return $result['data'];
        }else{
            exception($result['msg'] );
        }
    }

        /**
     * 批量获取审批实例
     * @param string $instance_id 实例id
     * @return void
     * @author Sam
     * @date 2022-10-25
     */
    public function get_approval_detail($instance_id){
        if(!$instance_id){
            json_response(0,'缺少审批实例唯一标识');
        }
        $tenant_access_token = $this->get_tenant_access_token();
        $data = [];
        $data['header'] = ['Authorization:Bearer '.$tenant_access_token];
        $result = curl('get',$this->approval_url.'/'.$instance_id,$data);
        $result = json_decode($result,true);
        if(isset($result['code']) && $result['code'] == 0){
            return $result['data'];
        }else{
            exception($result['msg'] );
        }
    }
   
}
